package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.SysOssDao;
import com.sugon.entity.SysOssEntity;
import com.sugon.service.SysConfigService;
import com.sugon.service.SysOssService;
import com.sugon.utils.MinioUtil;
import com.sugon.utils.R;
import com.sugon.utils.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("sysOssService")
public class SysOssServiceImpl implements SysOssService {

    @Autowired
    private SysOssDao sysOssDao;
    @Resource
    private SysConfigService configService;

    /**
     * queryObject
     *
     * @param id
     * @return
     */
    @Override
    public SysOssEntity queryObject(String id) {
        return sysOssDao.queryObject(id);
    }

    /**
     * queryList
     *
     * @param map
     * @return
     */
    @Override
    public List<SysOssEntity> queryList(Map<String, Object> map) {
        return sysOssDao.queryList(map);
    }

    /**
     * queryTotal
     *
     * @param map
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysOssDao.queryTotal(map);
    }

    /**
     * save
     *
     * @param sysOss
     */
    @Override
    public void save(SysOssEntity sysOss) {
        sysOss.setId(RandomUtil.randomString(32));
        sysOss.setCreateTime(DateUtil.date());
        sysOssDao.save(sysOss);
    }

    /**
     * update
     *
     * @param sysOss
     */
    @Override
    public void update(SysOssEntity sysOss) {
        sysOssDao.update(sysOss);
    }

    /**
     * delete
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        sysOssDao.delete(id);
    }

    /**
     * deleteBatch
     *
     * @param ids
     */
    @Override
    public void deleteBatch(String[] ids) {
        sysOssDao.deleteBatch(ids);
    }

    /**
     * upload
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public R upload(MultipartFile file) throws Exception {
        return upload("common", null, file);
    }

    /**
     * upload
     *
     * @param module
     * @param subModule
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public R upload(String module, String subModule, MultipartFile file) {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        // 获取文件初始名称
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        String fileUrl = null;
        // 添加水印
        // 需要对上传的工装图纸或者资料添加水印
        if ("tools".equals(module)) {
            // 设置临时文件,如果不存在则创建
            String temSavePath = configService.getTemSavePath();
            File tempFile = FileUtil.file(temSavePath, fileName);
            try {
                com.sugon.utils.FileUtil.setWatermark(file, tempFile);
                fileUrl = MinioUtil.upload(FileUtil.getInputStream(tempFile), buildBizPath(module, subModule), fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            fileUrl = MinioUtil.upload(file, buildBizPath(module, subModule));
        }
        if (StrUtil.isEmpty(fileUrl)) {
            return R.error("上传失败,请检查配置信息是否正确!");
        }

        // 获取文件名
        String orgName = file.getOriginalFilename();
        orgName = MinioUtil.getFileName(orgName);

        // 保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(fileUrl);
        this.save(ossEntity);

        R r = new R();
        // 设置下载链接
        r.put("url", fileUrl);
        // 文件相对路径/upload/images/1596192663894.jpg
        r.put("link", fileUrl);
        // 文件名称
        r.put("name", fileName);
        // 只包括文件名
        r.put("fileName", orgName);
        return r;
    }

    /**
     * 构建业务路径
     *
     * @param moduleNames
     * @return
     */
    private static String buildBizPath(String... moduleNames) {
        List<String> moduleNameList = CollectionUtil.newArrayList(moduleNames);
        // 移除空元素
        moduleNameList = moduleNameList.stream().filter(s -> StrUtil.isNotEmpty(s) && StrUtil.isNotEmpty(s.trim())).collect(Collectors.toList());
        return CollectionUtil.join(moduleNameList, "/", s -> s.trim());
    }

    @Override
    public R upload(String module, MultipartFile file) throws Exception {
        return upload(module, null, file);
    }

}
